package club.jdiy.dev.zlt.controller;

import club.jdiy.admin.entity.Menu;
import club.jdiy.admin.interceptor.GuestDisabled;
import club.jdiy.admin.util.IdUtil;
import club.jdiy.core.base.JDiyCtrl;
import club.jdiy.core.base.domain.Pager;
import club.jdiy.dev.controller.JDiyController;
import club.jdiy.dev.dao.JDiyUiDao;
import club.jdiy.dev.types.UiTpl;
import club.jdiy.dev.zlt.service.JDevPageService;
import club.jdiy.dev.entity.JDiyUi;
import club.jdiy.core.ex.JDiyException;
import club.jdiy.dev.zlt.service.JDevMenuService;
import club.jdiy.core.base.domain.Ret;
import club.jdiy.utils.ArrayUtils;
import club.jdiy.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("mgmt/JDiyAdmin")
public class JDevMenuCtrl extends JDiyCtrl<Menu, JDevMenuService> implements JDiyController {

    @RequestMapping(value = "menu.list")
    public String ls(Menu qo, String orderField, String orderDirection,
                     @RequestParam(defaultValue = "0") Integer pageSize,
                     @RequestParam(defaultValue = "1") Integer page,
                     ModelMap map) {
        Pager<Menu> pager = service.findPager(pageSize, page, qo, orderField, orderDirection);
        map.put("qo", qo);
        map.put("pager", pager);
        map.put("orderField", orderField);
        map.put("orderDirection", orderDirection);
        map.put("nodes", service.findRootList());
        map.put("uiTplMap", Arrays.stream(UiTpl.values()).collect(Collectors.toMap(Enum::name, t -> t, (a, b) -> b)));

        Map<String, JDiyUi> uis = new HashMap<>();
        List<Menu> alls = service.findAll();
        alls.stream().filter(mm -> !StringUtils.isEmpty(mm.getUid()) && !uis.containsKey(mm.getUid()))
                .forEach(mm -> jDiyPageService.findById(mm.getUid()).ifPresent(pg -> uis.put(mm.getUid(), pg)));
        map.put("uis", uis);

        return "menu.ls";
    }

    @RequestMapping("menu.form")
    public String in(String id, ModelMap map, HttpServletRequest request) throws Exception {
        map.put("rootList", service.findRootList());
        map.put("fatherId", request.getParameter("fatherId"));
        map.put("uiList", jDiyPageService.findAll());
        map.put("UiTplList", UiTpl.values());
        if (StringUtils.isEmpty(id) || "0".equals(id)) {
            map.put("vo", new JDiyUi("0"));
        } else {
            service.findById(id).ifPresent(po -> {
                map.put("vo", po);
                Collection<String> userRealms = StringUtils.hasText(po.getRealms())
                        ? Arrays.stream(po.getRealms().replaceAll("\r", "").replaceAll("\\n+", "\n").split("\n")).collect(Collectors.toCollection(LinkedHashSet::new))
                        : new LinkedHashSet<>(), sysRealms;
                if (!StringUtils.isEmpty(po.getType()) && !"url".equals(po.getType())) {
                    try {
                        sysRealms = uiDao.getRealms(po.getUid());
                    } catch (Exception ex) {
                        sysRealms = new ArrayList<>();
                    }
                    userRealms = ArrayUtils.subtract(userRealms, sysRealms);
                } else {
                    sysRealms = new ArrayList<>();
                }
                map.put("sysRealms", ArrayUtils.join(sysRealms, "@##@"));
                map.put("userRealms", ArrayUtils.join(userRealms, "@##@"));
            });
        }

        return "menu.in";
    }

    @GuestDisabled
    @RequestMapping("menu.save")
    @ResponseBody
    public Ret<?> save(Menu vo, HttpServletRequest request) {
        try {
            String oldId = request.getParameter("oldId");
            if (StringUtils.isEmpty(vo.getId()) || "0".equals(vo.getId())) vo.setId(IdUtil.newId());
            /*if (!StringUtils.isEmpty(vo.getType()) && !"url".equals(vo.getType())) {
                ButtonRealms uiMeta = uiService.getUiMeta(vo.getUid());
                if (uiMeta != null) vo.setRealms(uiMeta.getRealms());
            }*/
            if (StringUtils.hasText(vo.getRealms())) {
                vo.setRealms(vo.getRealms().replaceAll("\\r", "")
                        .replaceAll("\\n+", "\n"));
            }
            service.doSave(oldId, vo);
            return Ret.success();
        } catch (JDiyException le) {
            return Ret.error(le);
        }
    }

    @GuestDisabled
    @RequestMapping("menu.delete.{id}")
    @ResponseBody
    public Ret<String> delete(@PathVariable String id) {
        try {
            service.delete(new Menu(id));
            return Ret.success();
        } catch (JDiyException le) {
            return Ret.error(le);
        } catch (Exception le) {
            return Ret.fail(Ret.RetCode.fail.getCode(), "对不起，删除失败，可能此条目已被系统业务使用。");
        }
    }


    @RequestMapping("menu.getUiRealms.{uid}")
    @ResponseBody
    public Ret<List<String>> getUiRealms(@PathVariable String uid) {
        try {
            return Ret.success(uiDao.getRealms(uid));
        } catch (Exception le) {
            return Ret.error(le);
        }
    }


    @Resource
    private JDevPageService jDiyPageService;
    @Resource
    private JDiyUiDao uiDao;
}
